object ClosuresDemo extends App {
  def createResourceTracker(resourceId: String): (Double) => (String, Int, Double) = {
    var usageCount = 0
    var totalDuration = 0.0
    (duration: Double) => {
      usageCount += 1
      totalDuration += duration
      (resourceId, usageCount, totalDuration)
    }
  }

  val classroomTracker = createResourceTracker("R101教室")
  val projectorTracker = createResourceTracker("P001投影仪")

  println("=== 资源使用记录===")
  println(classroomTracker(2.0))
  println(projectorTracker(1.5))
  println(classroomTracker(3.0))
  println(projectorTracker(2.0))
  println(classroomTracker(1.5))

  def createAccumulator(initialValue: Double): (Double) => Double = {
    var total = initialValue
    (amount: Double) => {
      total += amount
      total
    }
  }

  val attendanceAccumulator = createAccumulator(0.0)
  println("\n===学生出勤统计===")
  println(s"第1周出勤: ${attendanceAccumulator(32.0)} 人")
  println(s"第2周出勤: ${attendanceAccumulator(30.0)} 人")
  println(s"第3周出勤: ${attendanceAccumulator(31.0)} 人")
  println(s"总出勤: ${attendanceAccumulator(0.0)} 人")

  def createGradeCounter(passLine: Double, goodLine: Double, excellentLine: Double): (Double) => Map[String, Int] = {
    var counts = Map(
      "不及格" -> 0,
      "及格" -> 0,
      "良好" -> 0,
      "优秀" -> 0
    )
    (score: Double) => {
      val grade =
        if (score >= excellentLine) "优秀"
        else if (score >= goodLine) "良好"
        else if (score >= passLine) "及格"
        else "不及格"
      counts = counts + (grade -> (counts(grade) + 1))
      counts
    }
  }

  val strictGradeCounter = createGradeCounter(60.0, 80.0, 90.0)
  println("\n=== 成绩等级统计===")
  val scores = List(85.0, 92.0, 58.0, 76.0, 88.0, 90.0, 65.0, 72.0, 45.0, 80.0)
  scores.foreach { score =>
    val result = strictGradeCounter(score)
    println(s"加入 $score 分后: $result")
  }

  def createUniqueIdGenerator(prefix: String): () => String = {
    var counter = 0
    () => {
      counter += 1
      s"$prefix-$counter"
    }
  }

  val studentIdGenerator = createUniqueIdGenerator("S")
  val courseIdGenerator = createUniqueIdGenerator("C")
  println("\n=== 唯一-ID生成 ===")
  println(studentIdGenerator())
  println(studentIdGenerator())
  println(courseIdGenerator())
  println(studentIdGenerator())
  println(courseIdGenerator())
}
